﻿using Emgu.CV;
using Emgu.CV.Structure;
using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Vtron.LEDCorrective.Core;

namespace Vtron.LEDCorrective
{
    /// <summary>
    /// ImageWindow.xaml 的交互逻辑
    /// </summary>
    public partial class ImageWindow : Window
    {
        public ImageWindow(int partitionNum)
        {
            InitializeComponent();

            this.partitionNum = partitionNum;
            Refresh();
        }

        private bool isMouseLeftButtonDown = false;
        Point previousMousePoint = new Point(0, 0);
        int partitionNum = 0;
        private void MasterImage_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            ContentControl image = sender as ContentControl;
            if (image == null)
            {
                return;
            }
            TransformGroup group = ImageComparePanel.FindResource("ImageCompareResources") as TransformGroup;
            Point point = e.GetPosition(image);
            double scale = e.Delta * 0.001;
            ZoomImage(group, point, scale);
        }

        private static void ZoomImage(TransformGroup group, Point point, double scale)
        {
            Point pointToContent = group.Inverse.Transform(point);
            ScaleTransform transform = group.Children[0] as ScaleTransform;
            if (transform.ScaleX + scale < 1)
            {
                return;
            }
            transform.ScaleX += scale;
            transform.ScaleY += scale;
            TranslateTransform transform1 = group.Children[1] as TranslateTransform;
            transform1.X = -1 * ((pointToContent.X * transform.ScaleX) - point.X);
            transform1.Y = -1 * ((pointToContent.Y * transform.ScaleY) - point.Y);
        }

        private void MasterImage_MouseMove(object sender, MouseEventArgs e)
        {
            ContentControl image = sender as ContentControl;
            if (image == null)
            {
                return;
            }
            if (this.isMouseLeftButtonDown && e.LeftButton == MouseButtonState.Pressed)
            {
                this.DoImageMove(image, e.GetPosition(image));
            }
        }

        private void DoImageMove(ContentControl image, Point position)
        {
            TransformGroup group = ImageComparePanel.FindResource("ImageCompareResources") as TransformGroup;
            TranslateTransform transform = group.Children[1] as TranslateTransform;
            transform.X += position.X - this.previousMousePoint.X;
            transform.Y += position.Y - this.previousMousePoint.Y;
            this.previousMousePoint = position;
        }

        private void MasterImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            ContentControl image = sender as ContentControl;
            isMouseLeftButtonDown = true;
            previousMousePoint = e.GetPosition(image);
        }

        private void MasterImage_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            isMouseLeftButtonDown = false;
        }

        private void red_RadioButton_Click(object sender, RoutedEventArgs e)
        {
            Refresh();
        }

        private void green_RadioButton_Click(object sender, RoutedEventArgs e)
        {
            Refresh();
        }

        private void blue_RadioButton_Click(object sender, RoutedEventArgs e)
        {
            Refresh();
        }

        private void fitting_CheckBox_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Refresh();
        }

        private void thresholdBinary_CheckBox_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Refresh();
        }

        private void Refresh()
        {
            if (red_RadioButton.IsChecked == true)
            {
                SetImageSource("Red");
            }
            else if (green_RadioButton.IsChecked == true)
            {
                SetImageSource("Green");
            }
            else if (blue_RadioButton.IsChecked == true)
            {
                SetImageSource("Blue");
            }
        }

        private void SetImageSource(string color)
        {
            CorrectiveEngine.Instance.Id = new Guid("d09dcaba-e119-4855-be32-2b42f239698c");
            string directoryPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\Vtron\\LEDCorrective";
            string fileName = String.Format("{0}\\{1}_{2}_{3}.tiff", directoryPath, CorrectiveEngine.Instance.Id, partitionNum, color);

            if (File.Exists(fileName))
            {
                if (fitting_CheckBox.IsChecked == false && thresholdBinary_CheckBox.IsChecked == false)
                {
                    BitmapImage genBmpImage = new BitmapImage();
                    genBmpImage.BeginInit();
                    genBmpImage.UriSource = new Uri(fileName);
                    genBmpImage.EndInit();
                    MasterImage.Source = genBmpImage;
                }
                else
                {
                    string sourceImageFileName = fileName;
                    Image<Bgr, Byte> imageSource = new Image<Bgr, byte>(sourceImageFileName); //获取源图像
                    Image<Gray, Byte> imageGray = imageSource.Convert<Gray, Byte>(); //将源图像转换成灰度图像
                    int thresholdValue = 30; //用于二值化的阀值
                    Image<Gray, Byte> imageThreshold = imageGray.ThresholdBinary(new Gray(thresholdValue), new Gray(255d)); //对灰度图像二值化

                    Image<Bgr, Byte> imageResult = null;
                    if (thresholdBinary_CheckBox.IsChecked == true)
                    {
                        imageResult = imageThreshold.Convert<Bgr, Byte>();         //结果图像
                    }
                    else
                    {
                        imageResult = imageSource;
                    }

                    int i = 0;
                    Contour<System.Drawing.Point> contour = imageThreshold.FindContours();
                    for (var c = contour; c != null; c = c.HNext)
                    {
                        if (c.Total >= 3 && c.Total < 30)
                        {
                            i++;

                            if (fitting_CheckBox.IsChecked == true)
                            {
                                System.Drawing.PointF center;
                                float radius;
                                CvInvoke.cvMinEnclosingCircle(c.Ptr, out center, out radius);
                                imageResult.Draw(new CircleF(center, radius), new Bgr(System.Drawing.Color.Red), 1);
                            }
                        }
                    }

                    System.Drawing.Bitmap m_Bitmap = imageResult.ToBitmap();
                    IntPtr ip = m_Bitmap.GetHbitmap();
                    BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                        ip, IntPtr.Zero, Int32Rect.Empty,
                        System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());

                    MasterImage.Source = bitmapSource;
                    m_Bitmap.Save("d:\\001.jpg");
                }
            }
        }
    }
}
